<template>
  <div class="app-container">
    <div class="filter-container" >
      <span v-if="roles=='admin'">
        <el-input size="small" v-model.trim="listQuery.admin_name" placeholder="账户" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-select size="small" v-model="listQuery.admin_status" placeholder="状态" clearable style="width: 90px;" class="filter-item">
          <el-option v-for="item in importanceOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 20px">
          查询
        </el-button>
      </span>


      <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate"  v-if="roles!='plain'">
        新增
      </el-button>

    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="登录账户" width="210">
        <template slot-scope="scope">
          {{ scope.row.admin_name }}
        </template>
      </el-table-column>
      <el-table-column label="企业名称/项目名"  width="210">
        <template slot-scope="scope">
          {{ scope.row.enterprise_name }}
        </template>
      </el-table-column>
      <el-table-column label="角色"  width="100">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="头像"  align="center" >
        <template slot-scope="scope">
          <viewer>
            <img :src="scope.row.admin_head" width="50" height="50" alt="">
          </viewer>
        </template>
      </el-table-column>

      <el-table-column label="可添加的程序数量" width="100">
        <template slot-scope="scope">
          {{ scope.row.end_num}}
        </template>
      </el-table-column>

      <el-table-column label="账户过期时间" width="210">
        <template slot-scope="scope">
          {{ scope.row.end_time}}
        </template>
      </el-table-column>
      <el-table-column label="备注" width="300">
        <template slot-scope="scope">
          {{ scope.row.admin_remarks }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.admin_status | adminStatusFilter">
            <span v-if="scope.row.admin_status==0">正常</span>
            <span v-else>禁用</span>
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.admin_create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <span v-if="checkUser(row)">
            <el-button type="danger"  size="mini" @click="updateStatus(row)" v-if="row.admin_status==0" style="margin-left: 10px">
              设为禁用
            </el-button>
            <el-button type="success"  size="mini" @click="updateStatus(row)" v-if="row.admin_status==1" style="margin-left: 10px">
              设为启用
            </el-button>
            <el-button  size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </span>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="dialogFormClose">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="50px" style="width: 700px; margin-left:50px;">

        <el-form-item label="角色" prop="admin_roles" label-width="70px" v-if="roles==='admin'">
          <el-select v-model="temp.admin_roles" placeholder="请选择">
            <el-option
              v-for="item in auth_group"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <div v-if="roles!='plain'">
          <el-form-item label="企业名称/项目名" label-width="120px">
            <el-input v-model="temp.enterprise_name" placeholder="请输入企业名称/项目名" />
          </el-form-item>
          <el-form-item label="可添加程序数量" prop="end_num" label-width="120px">
            <el-input type="number" v-model="temp.end_num" placeholder="请输入程序数量" />
          </el-form-item>
          <el-form-item label="账户过期时间" prop="end_time" label-width="120px">
            <el-date-picker
              v-model="temp.end_time"
              format  = "yyyy-MM-dd"
              value-format = "yyyy-MM-dd"
              type="date"
              placeholder="选择账户过期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="temp.admin_remarks" placeholder="备注" />
          </el-form-item>
          <el-form-item label="登录账户【作为唯一登录名称】" prop="admin_name" label-width="220px">
            <el-input v-model.trim="temp.admin_name" :disabled=" checkUserIs " placeholder="请输入登录账户[作为唯一登录名称]" />
          </el-form-item>
        </div>

        <div v-if="dialogStatus==='create'">
          <el-form-item label="密码" prop="admin_password">
            <el-input type="password" show-password v-model.trim="temp.admin_password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="确认密码" label-width="70px" prop="admin_password2">
            <el-input type="password" show-password v-model.trim="temp.admin_password2"  placeholder="请再次输入密码" />
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="密码">
            <el-input type="password" show-password v-model.trim="temp.admin_password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="确认密码" label-width="70px">
            <el-input type="password" show-password v-model.trim="temp.admin_password2" placeholder="请再次输入密码" />
          </el-form-item>
        </div>

        <el-form-item label="头像" prop="">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers = "tokenFig"
            accept=".jpg,.png,.jpeg,.gif"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error = "handleAvatarError"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getAdmin,delAdmin,createAdmin,updateAdmin,updateAdminStatus,getAuthGroup } from '@/api/admin'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  filters: {
    adminStatusFilter(status) {
      const statusMap = {
        0: 'success',
        1: 'danger'
      }
      return statusMap[status]
    },
  },
  data() {
    //验证两次密码
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.temp.admin_password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      auth_group:'',
      token:'',
      imageUrl:'',
      uploadUrl:process.env.VUE_APP_BASE_API+'/admin/index/headUpload',
      squareUrl:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      downloadLoading:false,
      table_name:'用户数据导出',
      importanceOptions:[
        {'label': '正常','value':0},
        {'label': '禁用','value':1},
      ],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        admin_name: undefined,
        admin_status: undefined,
      },
      list: null,
      listLoading: true,
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        admin_roles:[{ required: true, message: '角色不能为空', trigger: 'blur' }],
        end_num:[{ required: true, message: '程序数量不能为空', trigger: 'blur' }],
        end_time:[{ required: true, message: '过期时间不能为空', trigger: 'blur' }],
        admin_name: [{ required: true, message: '账户不能为空', trigger: 'blur' }],
        admin_password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        admin_password2: [{validator:validatePass2,trigger:'blur'}],
      },
      //新增和编辑数据
      temp: {

        admin_roles:undefined,
        end_num:undefined,
        end_time:undefined,
        admin_name: undefined,
        admin_password: undefined,
        admin_password2:undefined,
        admin_head: undefined,

      },
      dialogStatus:'',
      dialogFormVisible: false,
    }
  },
  created() {
    //获取数据
    this.fetchData()
    this.get_auth_group()
    console.log(this.checkUserIs)
  },
  computed:{
    checkUserIs(){
      if(this.roles!='plain'){
        return false
      }else{
        return true
      }
    },
    tokenFig(){
      return {token:getToken()}
    },
    ...mapGetters([
      'roles',
      'name'
    ])
  },
  methods: {
    // //只要是普通用户，只能
    checkUser(row){

      //不是普通账户
      if(this.roles!='plain' && row.admin_name!=this.name){
        return true;
      }else {
        return false;
      }
    },
    get_auth_group(){``
      getAuthGroup().then(res => {
        this.auth_group = res.data
      })

    },
    //查询
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    //关闭弹窗的新增和修改
    dialogFormClose(){
      this.resetTemp()
      this.dialogFormVisible = false
    },
    //按钮唤起新增
    handleCreate() {
      // this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //新增操作方法
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAdmin(this.temp).then((res) => {
            this.resetTemp()
            if(res.status==200){
              this.$notify({
                title: 'Success',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
              this.dialogFormVisible = false
              this.fetchData()
            }else{
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        admin_name: undefined,
        admin_password: undefined,
        admin_password2:undefined
      }
      this.temp.admin_head = ""
      this.imageUrl =  ""
    },
    //按钮唤起编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.imageUrl =  this.temp.admin_head
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //编辑操作方法
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          //console.log(tempData)
          updateAdmin(tempData).then((res) => {
            if(res.status==200){
              // const index = this.list.findIndex(v => v.admin_id === this.temp.admin_id)
              // this.list.splice(index, 1, this.temp)
              this.fetchData()
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
            }else{
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    //头像上传成功后，返回
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.temp.admin_head = file.response.path
    },
    //头像上传失败后，返回
    handleAvatarError(err, file) {
      this.$message.error('图片上传失败!');
    },
    //上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeAvatarUpload(file) {
      const isJPG = file.type;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (isJPG!="image/jpeg"&&isJPG!="image/jpg"&&isJPG!="image/png"&&isJPG!="image/gif") {
        this.$message.error('上传头像图片只能是 jpg/jpeg/png/gif 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //查询列表数据
    fetchData() {
      this.listLoading = true
      getAdmin(this.listQuery).then(response => {
        // this.list = response.data.items
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    //删除列表数据
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAdmin({admin_id:row.admin_id}).then(response => {
          // this.list = response.data.items
          if(response.status==200){
            this.$notify({
              title: 'Success',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          }else{
            this.$notify({
              title: 'Error',
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //禁用启用
    updateStatus(row){
      updateAdminStatus({admin_id:row.admin_id,admin_status:row.admin_status}).then(response => {
        // this.list = response.data.items
        if(response.status==200){
          this.$notify({
            title: 'Success',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        }else{
          this.$notify({
            title: 'Error',
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    }

  },
  components:{
    Pagination
  }
}
</script>
<style>
.filter-container{
  padding-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

